<template>
  <a-layout>
    <a-layout-content style="padding: 24px;">
      <div class="header">
        <a-breadcrumb>
          <a-breadcrumb-item>
            <router-link to="/Grant">授权管理</router-link>
          </a-breadcrumb-item>
          <a-breadcrumb-item>
            <a @click="goBack">{{ experimentSetName }}</a>
          </a-breadcrumb-item>
          <a-breadcrumb-item>{{ batchName }}</a-breadcrumb-item>
        </a-breadcrumb>
      </div>

      <!-- 实验数据表格 -->
      <a-table
          :columns="columns"
          :data-source="experimentData"
          :pagination="false"
          :scroll="{ y: '35vh' }"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'action'">
            <span>
              <a @click="handleViewImages(record)">查看图片</a>
            </span>
          </template>
        </template>
      </a-table>

      <!-- 批次文件表格 -->
      <a-table
          :columns="fileColumns"
          :data-source="fileData"
          :pagination="false"
          :scroll="{ y: '30vh' }"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'file_size'">
            {{ formatFileSize(record.file_size) }}
          </template>
          <template v-if="column.key === 'action'">
            <a-button
                :loading="record.downloading"
                @click="handleDownloadFile(record)"
            >
              {{ record.downloading ? `${record.progress}%` : '下载' }}
            </a-button>
          </template>
        </template>
      </a-table>
    </a-layout-content>
  </a-layout>
</template>

<script>
import {defineComponent} from 'vue';
import {message} from 'ant-design-vue';
import axiosInstance from '@/axios/axios.js';

export default defineComponent({
  name: 'AuthorizedExperiment',
  data() {
    return {
      experimentSetName: '',
      batchName: '',
      experimentData: [],
      fileData: [],
      columns: [
        {
          title: '实验名称',
          dataIndex: 'experiment_name',
          key: 'experiment_name'
        },
        {
          title: '描述',
          dataIndex: 'description',
          key: 'description'
        },
        {
          title: '创建者',
          dataIndex: 'creator',
          key: 'creator'
        },
        {
          title: '操作',
          key: 'action',
          width: 150
        }
      ],
      fileColumns: [
        {
          title: '文件名',
          dataIndex: 'name',
          key: 'name'
        },
        {
          title: '文件类型',
          dataIndex: 'file_type',
          key: 'file_type'
        },
        {
          title: '文件大小',
          dataIndex: 'file_size',
          key: 'file_size'
        },
        {
          title: '文件类别',
          dataIndex: 'file_category',
          key: 'file_category'
        },
        {
          title: '操作',
          key: 'action',
          width: 100
        }
      ]
    };
  },
  created() {
    // 从路由参数中获取数据
    const {experimentSetName, batchName, experimentData} = this.$route.query;
    this.experimentSetName = experimentSetName || '未知实验集';
    this.batchName = batchName || '未知批次';

    try {
      this.experimentData = JSON.parse(experimentData || '[]');
      console.log('Parsed experiment data:', this.experimentData);

      // 确保每个实验对象都有必要的属性，同时保留所有原始字段
      this.experimentData = this.experimentData.map(exp => ({
        ...exp,  // 保留所有原始字段
        key: exp.experiment_id || exp._temp_comment,
        experiment_name: exp.experiment_name || '未命名实验',
        description: exp.description || '',
        creator: exp.creator || ''
      }));

      console.log('Experiment data with all fields:', this.experimentData.map(exp => ({
        id: exp.experiment_id,
        name: exp.experiment_name,
        tx_hash: exp.tx_hash,
        height: exp.height,
        all_fields: Object.keys(exp)
      })));

      console.log('Processed experiment data:', this.experimentData);

      // 初始化批次文件数据
      try {
        const allData = JSON.parse(this.$route.query.allData || '{}');
        const batchFiles = allData.batchFiles || [];
        const currentBatchId = this.$route.query.batchId;
        this.fileData = batchFiles
            .filter(file => file.reference_id === currentBatchId)
            .map(file => ({
              ...file,
              key: file.file_id || file._temp_comment,
              downloading: false,
              progress: 0
            }));
        console.log('Processed file data:', this.fileData);
      } catch (error) {
        console.error('解析文件数据失败:', error);
        message.error('解析文件数据失败');
        this.fileData = [];
      }
    } catch (error) {
      console.error('解析实验数据失败:', error);
      message.error('解析实验数据失败');
      this.experimentData = [];
      this.fileData = [];
    }
  },
  methods: {
    formatFileSize(bytes) {
      if (!bytes) return '0 B';
      const k = 1024;
      const sizes = ['B', 'KB', 'MB', 'GB'];
      const i = Math.floor(Math.log(bytes) / Math.log(k));
      return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    },
    async handleDownloadFile(record) {
      if (record.downloading) return;

      // 更新文件状态
      const index = this.fileData.findIndex(f => f.file_id === record.file_id);
      if (index !== -1) {
        this.fileData[index].downloading = true;
        this.fileData[index].progress = 0;
      }

      try {
        // 获取授权信息
        const userAddress = this.$cookies.get("userAddress");
        const accessId = this.$route.query.accessId;
        if (!userAddress || !accessId) {
          console.error('Missing required auth info:', {userAddress, accessId});
          message.error('授权信息不完整');
          return;
        }

        // 检查并构造共享路径
        if (!record.relative_path) {
          throw new Error('文件路径不完整');
        }

        // 构造共享路径
        const sharedPath = `shared/${userAddress}/${accessId}/${record.relative_path}`;
        const encodedPath = encodeURIComponent(sharedPath);
        console.log('Downloading file:', {
          name: record.name,
          path: sharedPath,
          table_type: record.table_type
        });

        const response = await axiosInstance({
          method: "GET",
          url: `/download/file?relativePath=${encodedPath}`,
          responseType: "blob",
          onDownloadProgress: (progressEvent) => {
            if (progressEvent.total) {
              const progress = Math.round((progressEvent.loaded * 100) / progressEvent.total);
              if (index !== -1) {
                this.fileData[index].progress = progress;
              }
            }
          }
        });

        // 创建下载链接
        const blobUrl = window.URL.createObjectURL(new Blob([response.data]));
        const link = document.createElement('a');
        link.href = blobUrl;
        link.setAttribute('download', record.name);
        document.body.appendChild(link);
        link.click();
        link.remove();
        window.URL.revokeObjectURL(blobUrl);

        message.success('下载完成');
      } catch (error) {
        console.error('下载文件失败:', error);
        message.error(`下载失败: ${error.response?.data?.message || error.message}`);
      } finally {
        // 重置文件状态
        if (index !== -1) {
          this.fileData[index].downloading = false;
          this.fileData[index].progress = 0;
        }
      }
    },
    goBack() {
      this.$router.go(-1);
    },

    async getImagesBaseUrl(experimentId, experimentName) {
      try {
        // 获取当前用户名和地址
        const username = this.$cookies.get("username");
        const userAddress = this.$cookies.get("userAddress");
        if (!username || !userAddress) {
          console.error('Missing user info:', {username, userAddress});
          return null;
        }

        // 获取授权者信息
        const allData = JSON.parse(this.$route.query.allData || '{}');
        const experimentSet = allData.experimentSets?.[0];
        const grantorName = experimentSet?.creator;
        if (!grantorName) {
          console.error('Missing grantor name');
          return null;
        }

        const response = await axiosInstance({
          method: "POST",
          url: "/grant/getImages",
          data: {
            dataId: this.$route.query.experimentSetId, // 使用实验集ID进行权限验证
            experimentId: experimentId, // 使用实验ID获取图片
            username: username,
            userAddress: userAddress,
            grantorName: grantorName,
            experimentSetName: this.experimentSetName,
            batchName: this.batchName,
            experimentName: experimentName,
            accessId: this.$route.query.accessId
          },
        });
        console.log('Images base URL response:', response.data);
        return response.data?.data?.url;
      } catch (error) {
        console.error('获取图片基础URL失败:', error);
        return null;
      }
    },
    async handleViewImages(record) {
      try {
        // 获取该实验的图片数据
        const images = await this.filterImagesByExperimentId(record.experiment_id);
        console.log('Filtered images:', images);

        if (!images || images.length === 0) {
          message.warning('该实验下没有图片数据');
          return;
        }

        // 导航到图片页面
        this.$router.push({
          path: '/Grant/AuthorizedImage',
          query: {
            experimentSetName: this.experimentSetName,
            batchName: this.batchName,
            experimentName: record.experiment_name,
            experimentId: record.experiment_id,
            experimentSetId: this.$route.query.experimentSetId, // 添加实验集ID
            batchId: this.$route.query.batchId, // 添加批次ID
            imageData: JSON.stringify(images),
            allData: this.$route.query.allData, // 保持原始allData不变
            accessId: this.$route.query.accessId // 传递授权ID
          }
        });
      } catch (error) {
        console.error('处理图片数据失败:', error);
        message.error('处理图片数据失败');
      }
    },
    async filterImagesByExperimentId(experimentId) {
      var results = [];
      var allData = {};
      var experiment = null;
      var baseUrl = '';
      var allImages = [];
      var i, j, img, metadata, relativePath;

      try {
        // 解析数据
        allData = JSON.parse(this.$route.query.allData || '{}');

        // 查找实验
        if (allData.experiments) {
          for (i = 0; i < allData.experiments.length; i++) {
            if (allData.experiments[i].experiment_id === experimentId) {
              experiment = allData.experiments[i];
              break;
            }
          }
        }

        if (!experiment) {
          console.error('Experiment not found:', experimentId);
          return results;
        }

        // 获取基础URL
        baseUrl = await this.getImagesBaseUrl(experimentId, experiment.experiment_name);
        if (!baseUrl) {
          console.error('Failed to get base URL');
          return results;
        }

        // 优先收集image表的图片
        if (allData.images) {
          // 保留原始的table_type和path
          allImages = allData.images.map(img => ({
            ...img,
            table_type: img.table_type || 'image'  // 只在未设置时使用默认值
          }));
        }
        
        // 如果没有找到image表的数据，再从files和experimentFiles中收集图片
        if (allImages.length === 0) {
          const allFiles = [
            ...(allData.files || []),
            ...(allData.experimentFiles || [])
          ];
          
          console.log('No images found in image table, processing files:', {
            totalFiles: allFiles.length,
            files: allFiles
          });
          
          for (i = 0; i < allFiles.length; i++) {
            const file = allFiles[i];
            if (file.file_type === 'tif' ||
                file.file_type === 'png' ||
                file.file_type === 'jpg' ||
                file.file_type === 'jpeg' ||
                file.file_category === 'test_images') {
              console.log('Adding file to images:', file);
              allImages.push({...file, table_type: 'file'});
            }
          }
        }

        console.log('Collected images:', {
          total: allImages.length,
          fromImageTable: allImages.filter(img => img.table_type === 'image').length,
          fromFileTable: allImages.filter(img => img.table_type === 'file').length
        });

        // 处理图片
        for (i = 0; i < allImages.length; i++) {
          img = allImages[i];
          if (!img || !img.name) {
            continue;
          }

          // 查找对应的experimentFile
          const experimentFile = allData.experimentFiles?.find(file =>
            file.name === img.name && file.reference_id === experimentId
          );

          console.log('Found matching experimentFile:', {
            imageName: img.name,
            experimentFile: experimentFile
          });

          // 从experimentFiles中获取元数据
          const matchedFile = allData.experimentFiles?.find(file =>
            file.name === img.name && file.reference_id === experimentId
          );

          // 根据数据来源合并元数据
          if (img.table_type === 'image') {
            // 如果是image表的数据，优先使用image表的数据
            metadata = {
              width: img.width,
              height: img.height,
              colorSpace: img.colorSpace,
              colorType: img.colorType,
              fileSize: img.file_size,
              created_at: img.created_at,
              file_type: img.file_type,
              file_category: img.file_category,
              reference_type: img.reference_type,
              image_width: img.width ? `${img.width} pixels` : undefined,
              image_height: img.height ? `${img.height} pixels` : undefined,
              tx_hash: img.tx_hash
            };
          } else {
            // 如果是file表的数据，使用experimentFile的数据补充
            metadata = {
              width: matchedFile?.width || img.width,
              height: matchedFile?.height || img.height,
              colorSpace: matchedFile?.colorSpace || img.colorSpace,
              colorType: matchedFile?.colorType || img.colorType,
              fileSize: matchedFile?.file_size || img.file_size,
              created_at: matchedFile?.created_at || img.created_at,
              file_type: matchedFile?.file_type || img.file_type,
              file_category: matchedFile?.file_category || img.file_category,
              reference_type: matchedFile?.reference_type || img.reference_type,
              image_width: matchedFile?.width ? `${matchedFile.width} pixels` : undefined,
              image_height: matchedFile?.height ? `${matchedFile.height} pixels` : undefined,
              tx_hash: img.file_hash
            };
          }

          console.log('Merged metadata:', {
            name: img.name,
            metadata: metadata,
            matchedFile: matchedFile
          });

          // 记录原始图片数据
          console.log('Original image data:', {
            name: img.name,
            colorSpace: img.colorSpace,
            colorType: img.colorType,
            file_size: img.file_size,
            height: img.height,
            width: img.width,
            updated_at: img.updated_at,
            created_at: img.created_at,
            file_type: img.file_type,
            file_category: img.file_category,
            reference_type: img.reference_type,
            tx_hash: img.tx_hash,
            file_hash: img.file_hash
          });

          // 构建路径
          if (img.table_type === 'image') {
            // image表的数据优先使用原始路径，如果没有则构建
            relativePath = img.relative_path;
            if (!relativePath) {
              console.warn('Image from image table missing relative_path, constructing path:', img);
              relativePath = this.batchName + '/' + experiment.experiment_name + '/Images/' + img.name;
            }
          } else {
            // file表的数据构建完整路径
            relativePath = img.relative_path ||
                (this.batchName + '/' +
                    experiment.experiment_name + '/Images/' +
                    img.name);
          }

          console.log('Path construction:', {
            table_type: img.table_type,
            name: img.name,
            original_path: img.relative_path,
            constructed_path: relativePath
          });

          console.log('Image path construction:', {
            name: img.name,
            table_type: img.table_type,
            original_path: img.relative_path,
            constructed_path: relativePath
          });

          console.log('Creating image object from:', {
            name: img.name,
            table_type: img.table_type,
            path: img.path,
            relative_path: relativePath
          });

          // 创建图片对象，确保所有元数据字段都正确传递
          const imageObject = {
            key: img.table_type === 'image' ? img.image_id : (img.file_id || img._temp_comment || img.name),
            name: img.name,
            imgUrl: baseUrl + img.name,
            experiment_set_id: img.experiment_set_id || this.$route.query.experimentSetId,
            batch_id: img.batch_id || this.$route.query.batchId,
            experiment_id: img.experiment_id || experimentId,
            path: img.path,  // 保留原始完整路径
            relative_path: relativePath,
            table_type: img.table_type,  // 保留原始table_type
            // 直接使用原始字段而不是metadata对象
            width: img.width,
            height: img.height,
            colorSpace: img.colorSpace,
            colorType: img.colorType,
            file_size: img.file_size,
            created_at: img.created_at,
            file_type: img.file_type,
            file_category: img.file_category,
            reference_type: img.reference_type,
            reference_id: img.reference_id || experimentId,
            // 添加格式化的宽高
            image_width: img.width ? `${img.width} pixels` : undefined,
            image_height: img.height ? `${img.height} pixels` : undefined
          };

          console.log('Created image object:', {
            name: img.name,
            metadata_fields: {
              width: imageObject.width,
              height: imageObject.height,
              colorSpace: imageObject.colorSpace,
              colorType: imageObject.colorType,
              file_size: imageObject.file_size,
              created_at: imageObject.created_at,
              file_type: imageObject.file_type,
              file_category: imageObject.file_category,
              reference_type: imageObject.reference_type
            }
          });

          // 只有当是image表的数据时，才添加tx_hash
          if (img.table_type === 'image' && img.tx_hash) {
            imageObject.tx_hash = img.tx_hash;
          }

          results.push(imageObject);
        }

        console.log('Processed images:', results.length);
      } catch (error) {
        console.error('Error processing images:', error);
      }

      return results;
    }
  }
});
</script>

<style scoped>
.header {
  margin-bottom: 24px;
}
</style>